package org.shaka.db.sqlbuilder.sql;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import com.google.common.collect.Lists;

public class SqlUnion {
    private String union;
    private List<SqlSelect> selects;

    private SqlUnion(String union) {
        this.union = union;
        selects = Lists.newArrayList();
    }

    public static SqlUnion unionAll(SqlSelect... selects) {
        return new SqlUnion(" UNION ALL ").addUnion(selects);
    }

    public static SqlUnion union(SqlSelect... selects) {
        return new SqlUnion(" UNION ").addUnion(selects);
    }

    public SqlUnion addUnion(SqlSelect... selects) {
        this.selects.addAll(Arrays.asList(selects));
        return this;
    }

    public boolean hasParams() {
        for (SqlSelect sqlSelect : selects) {
            if (sqlSelect.hasParams())
                return true;
        }
        return false;
    }

    public List<Object> params() {
        List<Object> params = Lists.newArrayList();
        for (SqlSelect sqlSelect : selects) {
            params.addAll(sqlSelect.params());
        }
        return params;
    }

    public String buildSql() {
        StringBuilder sb = new StringBuilder();
        buildSql(sb);
        return sb.toString();
    }

    public void buildSql(StringBuilder sb) {
        Iterator<SqlSelect> iter = selects.iterator();
        if (iter.hasNext()) {
            iter.next().buildSql(sb);
            while (iter.hasNext()) {
                sb.append(union);
                iter.next().buildSql(sb);
            }
        }
    }
}
